package org.weed.remote.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Map;

public class HttpRequest implements Runnable {
	private HttpConnection httpConnection;
	private ByteBuffer buffer;
	private Map<String, String> headers;
	
	public HttpRequest(HttpConnection httpConnection) {
		this.httpConnection = httpConnection;
		buffer = ByteBuffer.allocate(HttpConstants.BUFFER_SIZE);
		headers = new HashMap<String, String>();
	}
	
	
	/**
	 * Read Http Request from SocketChannel
	 */
	public void run() {		
		SocketChannel socketChannel = httpConnection.getSocketChannel();
		int bytesRead = 1;
		while (bytesRead > 0) {
			try {
				bytesRead = socketChannel.read(buffer);
				if (bytesRead == -1) {
					throw new HttpExceptions.RemoteHostClosedException();
				} else if (bytesRead > 0) {
					read(bytesRead);
				}
			} catch (Exception e) {
				e.printStackTrace();
				//httpConnection.disconnect();
			}
		}
		
		httpConnection.processHttpRequest();
	}
	
	private void read(int bytesToRead) {
		buffer.flip();
		String request = new String(buffer.array());
		System.out.println(request);
		BufferedReader reader = new BufferedReader(new StringReader(request));
		String line;
		try {
			//do {
				line = reader.readLine();
				System.out.println("@"+line);
				String[] a = line.split(" ");
				headers.put("mehtod", a[0]);
				headers.put("path", a[1]);
				
			//} while (line != null || !"".equals(line));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println(new String(buffer.array()));
	}
	
	public String getRequestPath() {
		return headers.get("path");
	}
	
	
	
	
	
	public String getRequestParameter(String param) {
		//TODO
		return "";
	}
	
	

}
